// pages/tobeTzThridStep/tobeTzThridStep.js
var url_js = require("../../utils/url.js");
var api = require("../../utils/apiRequest.js");
var ubt_js = require("../../utils/ubt.js");
var name_js = require("../../utils/ubtButtonName.js");
var common_js = require("../../utils/common.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    mdInfo: null,
    contentStatus: -1, //0未请求，1请求成功
    successUrl: url_js.imgUrl + "tobeTz_success.png",
    resultInfo: null, //请求成功返回数据
    codeFilePath: '' //二维码下载路径
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //2.初始化数据
    this.initData(options);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //初始化数据
  initData: function(options) {
    //1.解析数据
    //1.1门店信息
    let tmpMdInfo = common_js.jsonParse(options.mdInfo);
    this.setData({
      mdInfo: tmpMdInfo
    });
    //请求数据成为团长
    this.requestToShopApply(tmpMdInfo);
  },

  //请求数据成为团长
  requestToShopApply: function(res) {
    let data = {
      address: res.addressInfo.detailAddress,
      bankCardNo: res.dzInfo.bankNumbar,
      bankCardOwner: res.dzInfo.banKh,
      businessLicense: res.mdInfo.yyzzImgUrl,
      businessTime: res.timeInfo.begin + '-' + res.timeInfo.end,
      cityId: res.addressInfo.sxsId,
      districtId: res.addressInfo.districtId,
      geoLat: res.addressInfo.latitude,
      geoLon: res.addressInfo.longitude,
      hasShop: (res.hasShopIndex == 0 ? 1 : 0),
      idNo: res.dzInfo.card,
      mobile: res.dzInfo.phone,
      provinceId: res.addressInfo.ssId,
      realName: res.dzInfo.name,
      recommender: res.dzInfo.recommend,
      shopName: res.mdInfo.name,
      streetId: res.addressInfo.streetId,
      wechatNo: res.dzInfo.wechat
    };
    api.wxRequest(url_js.shopApplyUrl, data).then(res => {
      this.handleShopApplyResponseData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理成为团长的数据
  handleShopApplyResponseData: function(res) {
    //1.更新数据
    this.setData({
      resultInfo: res.result,
      contentStatus: 1
    });
    //2..提示
    common_js.showModal("提交成功！官方人员将主动电话联系您，以便核实更多信息。请保持您的手机畅通！");
  },

  //保存
  onSave: function() {
    //获取权限
    if (wx.saveImageToPhotosAlbum) {
      //1.获取设置
      wx.getSetting({
        success: res => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            //2.提前授权
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: res => {
                this.downloadTzImage();
              },
              fail: res => {
                //拒绝授权,打开设置
                this.openPhotosAlbumSetting(res);
              }
            })
          } else {
            //3.写入相册
            if (this.data.codeFilePath) {
              this.saveTzImageToPhotosAlbum(this.data.codeFilePath);
            } else {
              this.downloadTzImage();
            }
          }
        }
      })
    } else {
      common_js.showModal("当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。");
    }
  },

  //下载图片并且保存到相册
  downloadTzImage: function() {
    if (!this.data.resultInfo.codeUrl) {
      common_js.showToast("团长二维码不存在");
      return;
    }

    //下载团长二维码
    //1.loading
    common_js.showLoading();
    //2.download
    wx.downloadFile({
      url: this.data.resultInfo.codeUrl,
      success: res => {
        common_js.hideLoading();
        if (res.statusCode === 200) {
          this.setData({
            codeFilePath: res.tempFilePath
          });
          this.saveTzImageToPhotosAlbum(res.tempFilePath);
        } else {
          common_js.showToast("团长二维码下载失败！");
        }
      },
      fail: res => {
        common_js.hideLoading();
        common_js.showToast("团长二维码下载失败！");
      }
    });
  },

  //保存团长图片到相册
  saveTzImageToPhotosAlbum: function(tempFilePath) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.tobeTzThridStepSaveTzCode);
    
    wx.saveImageToPhotosAlbum({
      filePath: tempFilePath,
      success: res => {
        //alert
        common_js.showModal("小程序二维码保存成功！");
      }
    });
  },

  //提示打开相册权限
  openPhotosAlbumSetting: function(res) {
    //授权拒绝
    var firstAuthDeny = res.errMsg.indexOf("fail auth deny") != -1;
    if (firstAuthDeny) return;
    //提示打开设置
    common_js.showModal("亲，我们未获得您的相册授权，即将打开设置", null, true, null, null, () => {
      wx.openSetting({
        success: res => {
          var isOpenWriteAuth = res.authSetting['scope.writePhotosAlbum'];
          // 选择自提点
          if (isOpenWriteAuth) {
            this.downloadTzImage();
          }
        }
      })
    })
  },

  //返回角色选择首页
  onBack: function() {
    wx.navigateBack({
      delta: 3
    })
  },
})